package org.contextsensitivetodo.todoview;


import org.contextsensitivetodo.R;
import org.contextsensitivetodo.todoview.model.TodoItem;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.DialogInterface.OnClickListener;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class AddToDoActivity extends CSTodoActivity {
	private Button addButton;
	private Button cancelButton;
	private TextView todoNameText;

	private boolean changePending = false;
	private AlertDialog unsavedChangesDialog;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.addtodos); 
		setUpViews();
	}
	
	protected void addTodo() {
		if(!this.changePending){
			finish();
		}
		String todoName = todoNameText.getText().toString();
		TodoItem newTodoItem = new TodoItem();
		newTodoItem.setName(todoName);
		
		getCSTodoApplication().addToDo(newTodoItem);
		
		finish();
	}

	protected void cancel() {
		
		if(this.changePending){
			unsavedChangesDialog = new AlertDialog.Builder(this)
			.setTitle("Unsaved changes")
			.setMessage("message")
			.setPositiveButton("add task", new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					addTodo();
				}
			})
			.setNeutralButton("discard",  new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					finish();
				}
			})
			.setNegativeButton("cancel",  new OnClickListener() {
				
				public void onClick(DialogInterface dialog, int which) {
					unsavedChangesDialog.cancel();
					
				}
			})
			.create();
			
			unsavedChangesDialog.show();
			
			
		}else{
			finish();
		}
		
	}
	
	private void setUpViews() {
		addButton = (Button)findViewById(R.id.addButton);
		cancelButton = (Button)findViewById(R.id.cancelButton);
		todoNameText = (TextView)findViewById(R.id.todoname);
		
		addButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				addTodo();
			}
		});
		
		cancelButton.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				cancel();
			}
		});
		
		
		todoNameText.addTextChangedListener(new TextWatcher() {
			
			public void onTextChanged(CharSequence s, int start, int before, int count) {
				changePending = true;
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {}
			
			public void afterTextChanged(Editable s) {}
		});
	}

}
